package com.axcbd.demo.service;

import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@Service
public class VideoBackupService {

    private String videoStreamUrl = "http://localhost:5000/video_feed"; // 替换为你的 Python 服务 IP
    private String backupDirectory = "video_backups"; // 备份文件存放目录
    private Map<String, String> backupTasks = new HashMap<>(); // 存储备份任务信息
    private boolean isBackupRunning = false; // 标记备份是否正在运行

    public void startBackup() {
        if (isBackupRunning) {
            System.out.println("备份任务已在运行！");
            return;
        }

        isBackupRunning = true;
        System.out.println("开始备份视频流...");

        new Thread(() -> {
            try {
                // 创建备份目录
                File dir = new File(backupDirectory);
                if (!dir.exists()) {
                    dir.mkdirs();
                }

                // 获取当前时间格式化后的字符串，用于备份文件命名
                LocalDateTime startBackupTime = LocalDateTime.now();
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
                String backupFilePath = backupDirectory + "/backup_" + startBackupTime.format(formatter) + ".mjpeg";

                // 记录备份任务的开始时间和文件路径
                backupTasks.put("startTime", startBackupTime.format(formatter));
                backupTasks.put("backupFilePath", backupFilePath);

                // 发起 HTTP 请求获取视频流
                URL url = new URL(videoStreamUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setReadTimeout(0); // 设置读取超时为无限等待

                // 获取视频流输入流
                InputStream inputStream = connection.getInputStream();

                // 创建输出流，用于将视频流数据写入备份文件
                OutputStream outputStream = new FileOutputStream(backupFilePath);

                // 缓冲区用于读取和写入数据
                byte[] buffer = new byte[4096];
                int bytesRead;

                // 开始备份
                long backupStartTime = System.currentTimeMillis();
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);

                    // 检查是否超过24小时
                    long elapsedTime = (System.currentTimeMillis() - backupStartTime) / (1000 * 60 * 60);
                    if (elapsedTime >= 24) {
                        System.out.println("备份已达到24小时限制，备份任务结束。");
                        break;
                    }
                }

                // 关闭流和连接
                outputStream.close();
                inputStream.close();
                connection.disconnect();

                // 更新备份任务状态
                LocalDateTime endBackupTime = LocalDateTime.now();
                backupTasks.put("endTime", endBackupTime.format(formatter));
                backupTasks.put("status", "completed");

                System.out.println("视频流备份完成，备份文件：" + backupFilePath);

            } catch (IOException e) {
                e.printStackTrace();
                backupTasks.put("status", "failed");
                isBackupRunning = false;
            }
        }).start();
    }

    public Map<String, String> getBackupTasks() {
        return backupTasks;
    }
}